package com.ying.dogying.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.ying.dogying.entity.ImCategory;
import com.ying.dogying.entity.ImComment;
import com.ying.dogying.entity.ImPost;
import com.ying.dogying.entity.Response;
import com.ying.dogying.entity.dto.ImCommentDto;
import com.ying.dogying.entity.dto.ImPostDto;
import com.ying.dogying.utils.ValidationUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 李华明
 * @since 2020-06-01
 */
@Controller
@RequestMapping("/im-post")
public class ImPostController extends BaseController {

    private static final String CAPTCHA_SESSION_KEY = "CAPTCHA_SESSION_KEY";

    /**
     * 根据文章类型id查询文章(分页)
     */
    @GetMapping(value = "/category/{id:\\d*}")
    public String category(@PathVariable("id") Long id) {
        IPage<ImPostDto> category = imPostService.selectByParams(getPage(), id, null, null, null, "CREATE_TIME");
        request.setAttribute("currentCategoryId", id);
        request.setAttribute("category", category);
        return "post/category";
    }

    /**
     * 根据文章id查询文章详情、评论(分页)
     */
    @GetMapping(value = "/post/{id:\\d*}")
    public String detail(@PathVariable("id") Long id) {
        ImPostDto imPostDto = imPostService.selectOneByParams(id);
        Assert.notNull(imPostDto, "文章已被删除");

        imPostService.insertViewCount(imPostDto);

        // 1分页、2文章id、3用户id、排序
        IPage<ImCommentDto> comments = imCommentService.selectByParams(getPage(), imPostDto.getId(), null, "CREATE_TIME");
        request.setAttribute("comments", comments);
        request.setAttribute("post", imPostDto);
        request.setAttribute("currentCategoryId", imPostDto.getCategoryId());
        return "post/detail";
    }

    /**
     * 进入编辑文章页面
     */
    @GetMapping("/edit")
    public String edit() {
        String id = request.getParameter("id");
        ImPost imPost = new ImPost();
        if (StringUtils.isNotBlank(id)) {
            imPost = imPostService.getById(id);
            Assert.notNull(imPost, "文章已被删除");
            Long profileId = getProfileId();
            Assert.isTrue(imPost.getUserId().equals(profileId), "无权限编辑此文章");
            request.setAttribute("imPost", imPost);
        }
        List<ImCategory> categories = imCategoryService.list(new QueryWrapper<ImCategory>());
        request.setAttribute("categories", categories);
        return "post/edit";
    }

    /**
     * 编辑文章
     */
    @PostMapping("/edit")
    public @ResponseBody Response editSubmit(ImPost imPost, String captcha) {
        ValidationUtils.ValidResult validResult = ValidationUtils.validateBean(imPost);
        if(validResult.hasErrors()) {
            return new Response().failure(validResult.getErrors());
        }
        String kaptcha = SecurityUtils.getSubject().getSession().getAttribute(CAPTCHA_SESSION_KEY).toString();
        if (!kaptcha.equals(captcha)) {
            return new Response().failure("验证码不正确");
        }
        if(null == imPost.getId()) {
            imPost.setUserId(getProfileId());
            imPost.setCreateTime(new Date());
            imPost.setUpdateTime(new Date());
            imPost.setCommentCount(0);
            imPost.setEditMode(null);
            imPost.setLevel(0);
            imPost.setRecommend(false);
            imPost.setViewCount(0);
            imPost.setVoteDown(0);
            imPost.setVoteUp(0);
            imPostService.save(imPost);
        } else {
            ImPost tempPost = imPostService.getById(imPost.getId());
            Assert.isTrue(tempPost.getUserId().longValue() == getProfileId().longValue(), "无权限编辑此文章！");
            tempPost.setTitle(imPost.getTitle());
            tempPost.setContent(imPost.getContent());
            tempPost.setCategoryId(imPost.getCategoryId());
            imPostService.updateById(tempPost);
        }
        return new Response().success("发布成功").action("/im-post/post/" + imPost.getId());
    }

    /**
     * 删除文章
     */
    @PostMapping("/del")
    public @ResponseBody Response delete(Long id) {
        ImPost imPost = imPostService.getById(id);
        Assert.notNull(imPost, "该帖子已被删除");
        Assert.isTrue(imPost.getUserId()==getProfileId(), "无权限删除此文章！");

        imPostService.removeById(id);

        // 删除相关消息、收藏等
        imUserMessageService.removeByMap(MapUtil.of("post_id", id));
        imUserCollectionService.removeByMap(MapUtil.of("post_id", id));

        return new Response().success("删除成功").action("/");

    }

    /**
     * 设置置顶
     */
    @ResponseBody
    @PostMapping("/top")
    public Response jetSet(Long id, Integer rank, String field) {

        ImPost post = imPostService.getById(id);
        org.springframework.util.Assert.notNull(post, "该帖子已被删除");

        if("delete".equals(field)) {
            imPostService.removeById(id);
            return new Response().success();

        } else if("status".equals(field)) {
            post.setRecommend(rank == 1);

        }  else if("stick".equals(field)) {
            post.setLevel(rank);
        }
        imPostService.updateById(post);
        return new Response().success();
    }

    @Transactional
    @PostMapping("/reply")
    public @ResponseBody Response reply(Long jid, String content) {
        org.springframework.util.Assert.notNull(jid, "找不到对应的文章");
        org.springframework.util.Assert.hasLength(content, "评论内容不能为空");

        ImPost post = imPostService.getById(jid);
        org.springframework.util.Assert.isTrue(post != null, "该文章已被删除");

        ImComment comment = new ImComment();
        comment.setPostId(jid);
        comment.setContent(content);
        comment.setUserId(getProfileId());
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());
        comment.setLevel(0);
        comment.setVoteDown(0);
        comment.setVoteUp(0);
        imCommentService.save(comment);

        // 评论数量加一
        post.setCommentCount(post.getCommentCount() + 1);
        imPostService.updateById(post);

        // 本周热议数量加一
        // imPostService.incrCommentCountAndUnionForWeekRank(post.getId(), true);

        // 通知作者，有人评论了你的文章
        // 作者自己评论自己文章，不需要通知
//        if(comment.getUserId() != post.getUserId()) {
//            UserMessage message = new UserMessage();
//            message.setPostId(jid);
//            message.setCommentId(comment.getId());
//            message.setFromUserId(getProfileId());
//            message.setToUserId(post.getUserId());
//            message.setType(1);
//            message.setContent(content);
//            message.setCreated(new Date());
//            message.setStatus(0);
//            messageService.save(message);
//
//            // 即时通知作者（websocket）
//            wsService.sendMessCountToUser(message.getToUserId());
//        }

        // 通知被@的人，有人回复了你的文章
//        if(content.startsWith("@")) {
//            String username = content.substring(1, content.indexOf(" "));
//            System.out.println(username);
//
//            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            if(user != null) {
//                UserMessage message = new UserMessage();
//                message.setPostId(jid);
//                message.setCommentId(comment.getId());
//                message.setFromUserId(getProfileId());
//                message.setToUserId(user.getId());
//                message.setType(2);
//                message.setContent(content);
//                message.setCreated(new Date());
//                message.setStatus(0);
//                messageService.save(message);
//
//                // 即时通知被@的用户
//            }
//        }
        return new Response().success().action("/im-post/post/" + post.getId());
    }

}
